﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using HtmlAgilityPack;
using Super.Common;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using HAPHtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace Super.Tools
{


    public partial class Main : Form
    {

        public class ProductItem
        {
            public string Title { get; set; }
            public decimal Price { get; set; }
            public string Img { get; set; }
            public string Href { get; set; }
            public int VirtualCount { get; set; }
        }


        public static List<ProductItem> productItems = new List<ProductItem>();
        public int count = 0;
        public int nowCount = 0;
        string imgPath = ConfigurationManager.AppSettings["ImgPath"];
        private int UrlType = 0;//1=阿里巴巴 2=淘宝网
        private bool IsList = false;
        public Main()
        {
            Sunisoft.IrisSkin.SkinEngine se = null;
            se = new Sunisoft.IrisSkin.SkinEngine();
            se.SkinAllForm = true;
            se.SkinFile = Application.StartupPath + "//Wave.ssk";

            InitializeComponent();
        }

        private void btOK_Click(object sender, EventArgs e)
        {

            var alibabaUrl = this.tbAlibabaUrl.Text;
            var taobaoUrl = this.tbTaobaoUrl.Text;
            //  var url = "http://li117981039.cn.alibaba.com/page/offerlist.htm?pageNum=3";

            if (!string.IsNullOrEmpty(alibabaUrl))
            {
                if(alibabaUrl.Contains("offerlist"))
                {
                    var html = HttpHelper.GetWebRequest(alibabaUrl);
                    var htmlDoc = new HAPHtmlDocument();
                    htmlDoc.LoadHtml(html);
                    HtmlNodeCollection list = htmlDoc.DocumentNode.SelectNodes(@"//*[@class='offer-list-row']/li");
                    foreach (var item in list)
                    {
                        var model = new ProductItem();
                        model.Img = item.SelectSingleNode(@"./div[1]/a/img").Attributes["src"].Value;
                        model.Price = item.SelectSingleNode(@"./div[2]/em").InnerText.ToDecimal(0);
                        model.VirtualCount = item.SelectSingleNode(@"./div[5]/span").InnerText.ToInt(0);
                        var note = item.SelectSingleNode(@"./div[3]/a");
                        model.Href = note.Attributes["href"].Value;

                        model.Title = note.Attributes["title"].Value;
                        model.Img = HttpHelper.SaveImage(model.Img, imgPath);
                        productItems.Add(model);
                    }

                    UrlType = 1;
                    IsList = true;
                }
                else
                {
                    wb_Detail.Navigate(alibabaUrl);
                    UrlType = 1;
                    IsList = false;
                }
              
            }

            if(!string.IsNullOrEmpty(taobaoUrl))
            {
                if(taobaoUrl.Contains("item"))
                {
                    wb_Detail.Navigate(taobaoUrl);
                    UrlType = 2;
                    IsList = false;
                }
                else
                {
                    var html = HttpHelper.GetWebRequest(taobaoUrl);
                    var htmlDoc = new HAPHtmlDocument();
                    htmlDoc.LoadHtml(html);
                    HtmlNodeCollection list = htmlDoc.DocumentNode.SelectNodes(@"//*[@class='shop-list']/li/div");
                    foreach (var item in list)
                    {
                        var model = new ProductItem();

                        var tempImg = item.SelectSingleNode(@"./div[1]/a/img").Attributes["src"];
                        if (tempImg == null)
                        {
                            tempImg = item.SelectSingleNode(@"./div[1]/a/img").Attributes["data-ks-lazyload"];
                        }
                        model.Img = tempImg.Value;
                        model.Price = item.SelectSingleNode(@"./div[3]/strong").InnerText.Split(' ')[0].ToDecimal(0);
                        model.VirtualCount = item.SelectSingleNode(@"./div[4]/em").InnerText.ToInt(0);
                        var note = item.SelectSingleNode(@"./div[2]/a");
                        model.Href = note.Attributes["href"].Value;
                        model.Title = note.InnerText.RemoveHtmlTaget();
                        model.Img = HttpHelper.SaveImage(model.Img, imgPath);
                        productItems.Add(model);
                    }
                    UrlType = 2;
                    IsList = true;
                }
               
            }

            count = productItems.Count;
            this.lbNowCount.Text = 1.ToString();
            this.lbTotalCount.Text = count.ToString();

            this.progressBar_List.Maximum = count;
            this.progressBar_List.Minimum = 0;
            this.progressBar_List.Step = 1;
            PickProcess();

        }

        public void PickProcess()
        {

            if (nowCount < count)
            {
                this.wb_Detail.Navigate(productItems[nowCount].Href);
                this.progressBar_List.PerformStep();
                this.llbCurrent.Text = productItems[nowCount].Href;
                this.lbNowCount.Text = nowCount.ToString();
            }

        }

        private void btn_Pick_Click(object sender, EventArgs e)
        {
            var adp = new DbContextAdapter();
            var productService = new DGProductService(adp);
            var categoryService = new ProductCategoryService(adp);

            var encode = this.wb_Detail.Document.Encoding;//获取编码
            var url = this.wb_Detail.Url;
            //    var getReader = new System.IO.StreamReader(this.wb_Detail.Document.Body.InnerHtml, System.Text.Encoding.GetEncoding(encode));
            string html = wb_Detail.Document.Body.OuterHtml;

            var htmlDoc = new HAPHtmlDocument();
            htmlDoc.LoadHtml(html);


            string detail = "";
            decimal price = 0;
            string category = "";
            string title = "";
            string image = "";
            int VirtualCount = 0;
            HtmlNodeCollection imgList = null;
            if(UrlType==1)
            {
                detail = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='mod-detail-description']").InnerHtml;
                price = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='mod-detail-price']/table/tbody/tr[1]/td[2]/span[1]").InnerText.ToDecimal(0);
                category = htmlDoc.DocumentNode.SelectNodes(@"//*[@id='mod-detail-crumb-in']/ul/li/a").Last().InnerText;
                title = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='mod-detail-hd']/h1").InnerText;
                var tempimg = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@class='vertical-img']/a/img");
                image = tempimg.Attributes["src"].Value;
                var tempcount = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@class='mod-detail-sold']/div").InnerText;
                VirtualCount = GetNumber(tempcount).ToInt(0);
                imgList = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='mod-detail-description']").SelectNodes(@".//img[@src]");
            }

            if(UrlType==2)
            {
                var attributesNote = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='attributes']");
                detail = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='description']").InnerHtml;
                if(attributesNote!=null)
                {
                    var attributes = attributesNote.InnerHtml;
                    detail = attributes + "</br>" + detail;
                }
                price = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='J_StrPrice']").InnerText.ToDecimal(0);
                category = "淘宝网未分类";
                title = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@class='tb-detail-hd']/h3").InnerText;
                var tempimg = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='J_ImgBooth']");
                image = tempimg.Attributes["src"].Value;
                var tempcount = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@class='J_TDealCount']").InnerText;
                VirtualCount = tempcount.ToInt(0);
                imgList = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id='description']").SelectNodes(@".//img[@src]");

            }

            image = HttpHelper.SaveImage(image,imgPath);

           
            
            
            
            this.progressBarImg.Maximum = imgList.Count;
            this.progressBarImg.Minimum = 0;
            this.lbImgCount.Text = imgList.Count.ToString();
            this.progressBarImg.Step = 1;

            foreach (var node in imgList)
            {
                var lazyload = node.Attributes["data-ks-lazyload"];
                var src = node.Attributes["src"].Value;

                if (lazyload != null)
                {
                    src = lazyload.Value;
                }
                var newImg = HttpHelper.SaveImage(src, imgPath);
                detail = detail.Replace(src, newImg);
                this.progressBarImg.PerformStep();
            }


            var productCategory = categoryService.Repository.Find(a => a.Name.Contains(category) || category.Contains(a.Name)).FirstOrDefault();
            if (productCategory == null)
            {
                productCategory = new ProductCategory();
                productCategory.Name = category.Trim();
                productCategory.MaxCount = 0;
                productCategory.MinCount = 0;
                productCategory.ReMark = "这个分类是采集自动创建的";
                productCategory.Unit = "待修改";
                categoryService.Repository.InsertOrUpdate(productCategory);
                adp.SaveChanges();
            }
            var model = new DGProduct();
            model.ProductLink = this.wb_Detail.Url.ToString();
            model.Category_ID = productCategory.ID;
            model.Description = detail;
            model.CreateTime = DateTime.Now;
            model.State = 0;
            if(IsList)
            {
                var item = productItems.FirstOrDefault(a => a.Href == url.ToString());
                model.Title = item.Title;
                model.Img = item.Img;
                model.VirtualCount = item.VirtualCount;
                if (price > item.Price)
                {
                    item.Price = price;
                }
                model.CBPrice = item.Price;
                model.LSPrice = item.Price * (decimal)1.3;

                productService.Repository.InsertOrUpdate(model);
                adp.SaveChanges();
                nowCount += 1;
                PickProcess();
                this.progressBarImg.ResetText();
                this.progressBarImg.ResetRightToLeft();
            }
            else
            {
                model.Title = title;
                model.Img = image;
                model.VirtualCount = VirtualCount;
                model.CBPrice = price;
                model.LSPrice = price*(decimal) 1.3;
                productService.Repository.InsertOrUpdate(model);
                adp.SaveChanges();
                MessageBox.Show(string.Format("{0}-----采集完成！", title));
            }
         
        }

        private void btnSkip_Click(object sender, EventArgs e)
        {
            nowCount += 1;
            PickProcess();
        }

        /// <summary>
        /// 提取字符串中的数字字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetNumber(String str)
        {

            string returnStr = string.Empty;
            for (int i = 0; i < str.Length; i++)
            {
                if (Char.IsNumber(str, i) == true)
                {
                    string sdfsdfsd = str.Substring(i, 1);
                    returnStr += str.Substring(i, 1);
                }
                else
                {
                    string sss = str.Substring(i, 1);
                    if (str.Substring(i, 1) == "A" || str.Substring(i, 1) == " ")
                    {
                        returnStr += str.Substring(i, 1);
                    }
                }

            }
            return returnStr;
        }
    }
}
